<template>
  <div class="mb-4 flex justify-between">
    <n-space>
      <n-input v-model:value="carmiState.searchValue" placeholder="搜索授权码" @update:value="changeSearchVal" clearable />
      <n-button :disabled="!carmiState.checkedRowKeys.length" type="error"
        @click="delCarmi(carmiState.checkedRowKeys)">删除选中
      </n-button>
    </n-space>
    <div>
      <n-button type="primary" @click="openCarmiModal('add')">创建卡密
      </n-button>
    </div>
  </div>

  <n-data-table :bordered="false" :checked-row-keys="carmiState.checkedRowKeys" :columns="carmiState.columns"
    :data="carmiState.data" :pagination="pagination" :row-key="row => row.id" remote size="large" flex-height
    @update:checked-row-keys="rows => carmiState.checkedRowKeys = rows" :scroll-x="900" :loading="mainStore.pageLoading">
    <template #empty>
      <n-empty description="暂无卡密"></n-empty>
    </template>
  </n-data-table>

  <BasicModal :title="carmiState.modalInfo.positiveText + '卡密'" to="#app" @confirm="addEditCarmi"
    @register="carmiModalRegister">
    <n-form ref="carmiFormRef" :model="carmiState.formData" :rules="carmiState.rules" size="large"
      require-mark-placement="right-hanging" label-placement="top">
      <div v-if="carmiState.modalInfo.positiveText === '创建'">
        <n-form-item label="卡密数量" path="count">
          <n-input-number class="w-full" v-model:value="carmiState.formData.count" min="1" max="100" clearable
            placeholder="请输入要创建的卡密数量" />
        </n-form-item>
        <n-form-item label="卡密授权天数（-1为永久）" path="day">
          <n-input-number class="w-full" v-model:value="carmiState.formData.day" min="-1" clearable
            placeholder="请输入卡密授权的天数" />
        </n-form-item>
      </div>
      <div v-else>
        <n-form-item label="设备码" path="machine" label-placement="left">
          <n-input type="textarea" v-model:value="carmiState.formData.machine" placeholder="请输入设备码" />
        </n-form-item>
        <n-form-item label="使用状态" label-placement="left" path="state">
          <n-radio-group v-model:value="carmiState.formData.state">
            <n-radio :value="0">未使用</n-radio>
            <n-radio :value="1">使用中</n-radio>
            <n-radio :value="2">封禁</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="到期时间" label-placement="left" path="expirationAt">
          <n-date-picker class="w-full" v-model:value="carmiState.formData.expirationAt" :actions="['clear', 'confirm']"
            type="datetime" clearable :is-date-disabled="ts => ts < Date.now()" :shortcuts="carmiState.shortcuts" />
        </n-form-item>
      </div>
    </n-form>
  </BasicModal>
</template>

<script setup>
import { useNotification, NSpace, NButton, NDescriptions, NDescriptionsItem, NTag, NIcon } from 'naive-ui'
import { h, reactive, getCurrentInstance, defineAsyncComponent } from 'vue'
import { carmiList, deleteCarmi, updateCarmi, createCarmi } from '@api/carmiApi'
import { useMainStore } from '@/store'
import { timeFormat, copyText } from '@/utils'
import { useDialog } from '@/hook/popup/useDialog'
import { useModal } from '@c/Modal/useModal'
import { TrashOutline } from '@vicons/ionicons5'

const BasicModal = defineAsyncComponent(() => import('@c/Modal/BasicModal.vue'))
const { proxy } = getCurrentInstance()
const notification = useNotification()
const mainStore = useMainStore()

const carmiForm = {
  count: null,
  day: null,
}

const carmiState = reactive({
  creating: false,
  data: [],
  modalInfo: {
    positiveText: '',
  },
  searchValue: '',
  formData: {},
  shortcuts: {
    '明天此刻': () => new Date().getTime() + 24 * 60 * 60 * 1e3,
    '7天后': () => new Date().getTime() + 24 * 60 * 60 * 1e3 * 7,
    '30天后': () => new Date().getTime() + 24 * 60 * 60 * 1e3 * 7,
  },
  checkedRowKeys: [],
  rules: {
    count: { required: true, type: 'number', message: '创建数量不能为空', trigger: 'input' },
    day: { required: true, type: 'number', message: '授权天数不能为空', trigger: 'input' },
    machine: { required: true, message: '设备码不能为空', trigger: 'input' },
    expirationAt: { type: 'number', required: true, message: '到期时间不能为空', trigger: 'input' }
  },
  columns: [
    { type: 'selection' },
    {
      type: 'expand',
      renderExpand: row => {
        return h(NDescriptions, { columns: 1, labelPlacement: 'left' }, {
          default: () => [
            h(NDescriptionsItem, { label: '创建时间' }, {
              default: () => h(NTag, { type: 'primary', size: 'small' }, { default: () => timeFormat(row.createdAt) }),
            }),
            h(NDescriptionsItem, { label: '修改时间' }, {
              default: () => h(NTag, { type: 'primary', size: 'small' }, { default: () => timeFormat(row.updatedAt) }),
            }),
          ],
        })
      },
    },
    { title: 'id', key: 'id', minWidth: 90, width: 90 },
    { title: '授权码', key: 'content', minWidth: 160, ellipsis: { tooltip: true } },
    {
      title: '设备码', key: 'machine', minWidth: 160, ellipsis: { tooltip: true }, render(row) {
        return (row.machine || '暂无')
      }
    },
    {
      title: '使用状态', key: 'state', minWidth: 90, render(row) {
        let text, type
        switch (row.state) {
          case 0:
            text = '未使用'
            type = 'default'
            break
          case 1:
            text = '使用中'
            type = 'primary'
            break
          case 2:
            text = '封禁'
            type = 'error'
            break
        }
        return h(NTag, { type }, {
          default: () => text
        })
      }
    },
    {
      title: '授权天数', key: 'day', minWidth: 160, render(row) {
        if (row.day === -1) return '永久有效'
        return `${row.day}天`
      }
    },
    {
      title: '到期时间', key: 'expirationAt', minWidth: 160, render(row) {
        if (!row.expirationAt) return `未激活`
        return timeFormat(row.expirationAt)
      }
    },
    {
      title: '操作', minWidth: 120, width: 120,
      render(row) {
        return h(NSpace, {}, {
          default: () => [
            h(NButton, {
              type: 'primary',
              class: 'mt-1',
              size: 'small',
              onclick() {
                openCarmiModal('edit', row)
              },
            }, { default: () => '编辑' }),
            h(NButton, {
              type: 'error',
              size: 'small',
              title: '删除卡密',
              class: 'mt-1',
              onclick() {
                delCarmi([row.id])
              },
            }, { default: () => h(NIcon, { component: TrashOutline, size: 16 }, {}) }),
          ],
        })
      },
    }
  ],
})

const pagination = reactive({
  ...mainStore.pagination,
  onChange(page) {
    pagination.page = page
    getCarmiList()
  },
  onUpdatePageSize(pageSize) {
    pagination.page = 1
    pagination.pageSize = pageSize
    getCarmiList()
  },
})

const [
  carmiModalRegister, {
    openModal: basicOpenCarmiModal,
    closeModal: closeCarmiModal,
    setModalLoading: setCarmiModalLoading,
  }] = useModal(carmiState.modalInfo)

const openCarmiModal = (type, item = {}) => {
  carmiState.modalInfo.positiveText = type === 'add' ? '创建' : '修改'
  carmiState.formData = type === 'add' ? { ...carmiForm } : { ...item, expirationAt: item.expirationAt ? +new Date(item.expirationAt) : null }
  basicOpenCarmiModal()
}

const getCarmiList = async () => {
  try {
    mainStore.setPageLoading(true)
    const res = await carmiList({ page: pagination.page, limit: pagination.pageSize, search: carmiState.searchValue })
    if (res?.statusCode === 200) {
      carmiState.data = res.data.rows
      pagination.itemCount = res.data.count
    }
  } finally {
    mainStore.setPageLoading(false)
  }
}
getCarmiList()

const addEditCarmi = () => {
  proxy.$refs.carmiFormRef.validate(async validate => {
    if (validate) return false
    try {
      setCarmiModalLoading(true)
      let api = createCarmi
      let formData = { ...carmiState.formData }
      if (carmiState.modalInfo.positiveText === '修改') {
        api = updateCarmi
        formData.expirationAt = timeFormat(formData.expirationAt)
        const day = (carmiState.formData.expirationAt - Date.now()) / 86400000
        formData.day = day < 1 ? 1 : parseInt(day)
      }
      const res = await api(formData)
      if (res?.statusCode !== 200) return false
      closeCarmiModal()
      await getCarmiList()
      if (carmiState.modalInfo.positiveText === '创建') {
        let content = ''
        res.data.forEach(item => {
          content += item + '\n'
        })
        const n = notification.create({
          type: 'success',
          title: '创建卡密成功',
          meta: timeFormat(Date.now()),
          content: content,
          action: () => h(
            NButton,
            {
              text: true,
              type: 'success',
              onClick: () => {
                n.destroy()
                copyText(content)
              }
            },
            {
              default: () => '复制全部'
            }
          )
        });
      }else{
        $message.success(res.message)
      }
    } finally {
      setCarmiModalLoading(false)
    }
  })
}

const delCarmi = ids => {
  const delDialog = useDialog({
    title: '删除',
    content: `是否删除${carmiState.checkedRowKeys.length > 1 ? '这些' : '该'}卡密?`,
    type: 'error',
    icon: true,
    async confirm() {
      const res = await deleteCarmi({ id: [...ids] })
      if (res?.statusCode === 200) {
        delDialog.destroy()
        carmiState.checkedRowKeys = []
        await getCarmiList()
        $message.success(res.message)
      }
    },
  })
}

let timer = null
const changeSearchVal = val => {
  clearTimeout(timer)
  timer = setTimeout(() => {
    console.log(val);
    getCarmiList()
  }, 300)
}
</script>

<style lang="less" scoped></style>
